package com.youfang.sixthmedia.net;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

import com.gzit.common.async.AsynCallback;
import com.gzit.common.async.LoadingAsyncTask;
import com.gzit.common.async.LoadingCallback;
import com.youfang.sixthmedia.LoginActivity;

/**
 * 所有网络消息的出口
 * 
 * @author teddy
 * 
 */
public class Net {

	// //////////////////通用消息的拦截处理机制////////////////////////
	private static MessageInterceptor commonMessageInterceptor = MessageInterceptor.EMPTRY;

	public static void setupMessageInterceptor(MessageInterceptor interceptor) {
		commonMessageInterceptor = interceptor;

	}

	// //////////////////////////////////////////////

	// ////////////////////链式串行调用/////////////////
	public static Chain makeChain(ChainAsynCallbak<Response> callback,
			LoadingCallback loading) {
		return new Chain().prepare(callback, loading);

	}

	// ///////////////单次异步调用///////////////////////////

	public static AsyncTask<Request, Integer, Response> message(Activity ctx,
			MessageDelegate delegate, final AsynCallback<Response> callback) {
		return doHttpRemote(ctx, delegate.request(), delegate.response(),
				callback);
	}

	public static AsyncTask<Request, Integer, Response> message(Activity ctx,
			MessageDelegate delegate, final AsynCallback<Response> callback,
			final LoadingCallback loading) {
		return doHttpRemote(ctx, delegate.request(), delegate.response(),
				callback, loading);
	}

	public static AsyncTask<Request, Integer, Response> simpleMessage(
			MessageDelegate delegate, final AsynCallback<Response> callback) {
		return doSimpleHttpRemoter(delegate.request(), delegate.response(),
				callback);
	}

	/**
	 * 执行后台任务,不处理任何异常，不处理loading，不处理异常（异常由业务代码处理）
	 * 
	 * @param req
	 * @param resp
	 * @param callback
	 */
	public static AsyncTask<Request, Integer, Response> doSimpleHttpRemoter(
			final Request req, final Response resp,
			final AsynCallback<Response> callback) {

		return new AsyncTask<Request, Integer, Response>() {
			protected void onPostExecute(Response result) {
				callback.callback(result);
			};

			@Override
			protected Response doInBackground(Request... params) {
				resp.setType(req.getType());
				HttpRemoter.doRemote(req, resp);
				return resp;
			}

		}.execute(req);
	}

	/**
	 * 处理公共异常，处理loading等,业务接口基本从此地入手
	 * 
	 * @param ctx
	 * @param req
	 * @param resp
	 * @param callback
	 */
	// 异步执行HTTP请求
	public static AsyncTask<Request, Integer, Response> doHttpRemote(
			Activity ctx, final Request req, final Response resp,
			final AsynCallback<Response> callback) {
		return Net.doHttpRemote(ctx, req, resp, callback, null);
	}

	// 异步执行HTTP请求,重载loading对话框
	public static AsyncTask<Request, Integer, Response> doHttpRemote(
			Activity ctx, final Request req, final Response resp,
			final AsynCallback<Response> callback, final LoadingCallback loading) {

		return new LoadingAsyncTask<Request, Integer, Response>(ctx, loading) {

			@Override
			protected void onPostExecute(Response resp) {
				super.onPostExecute(resp);

				// 任务完成引发回调
				callback.onFinish(resp);

				// 服务端服务端点未部署，可以忽略该请求，则不做后续处理
				if (!req.isServerEndPointMandatory()
						&& resp.isServerEndPointMissing()) {
					Log.i("HttpRemoter", resp.getClass().getSimpleName()
							+ "服务地址不存在");
					return;

				}

				if (commonMessageInterceptor.after(ctx, req, resp)) {
					if (callback != null) {
						callback.callback(resp);
					}
				}

			}

			@Override
			protected Response doInBackground(Request... params) {
				resp.setType(req.getType());
				if (commonMessageInterceptor.before(ctx, req, resp)) {
					HttpRemoter.doRemote(req, resp);
				}
				return resp;
			}

		}.execute(req);

	}

	/**
	 * 通用消息拦截器
	 */
	static {
		commonMessageInterceptor = new MessageInterceptor() {

			@Override
			public boolean before(Activity ctx, Request req, Response resp) {

				// 测试机制，允许框架不向服务端点发起请求的情况下，返回结果
				if (req.getType() == Message.TYPE_FAKE) {
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

					return false;
				}

				// 真是的消息才向服务端点发起请求
				return true;
			}

			@Override
			public boolean after(Activity ctx, Request req, Response resp) {

				return handleCommonError(ctx, resp);
			}
		};
	}

	// 处理通用错误
	private static boolean handleCommonError(final Activity ctx, Response resp) {

		switch (resp.retcode) {

		// 会话过期，提示是否重新登录，或者退出应用
		case Response.ERROR_SESSION_TIME_OUT:

			return false;

			// 其它通用错误
		case Response.CODE_CLIENT_ERROR:
		case Response.CODE_ERROR:
			String content = resp.getError();

			return false;
		}

		switch (resp.errorcode) {
		case Response.CODE_AUTHORIZE_DENY:
			// user not logined... prompt user to do login...
			if (resp.shouldShowLoginWhenNeedFailAuthed()) {
				gotoLoginActivity(ctx);
			}

			break;

		}

		return true;

	}

	public static final int LOGIN_REQUEST_CODE = 1;

	public static void gotoLoginActivity(Activity fromActivity) {
		Intent intent = new Intent();
		intent.setClass(fromActivity, LoginActivity.class);
		fromActivity.startActivityForResult(intent, LOGIN_REQUEST_CODE);

	}
}
